package com.example.parallelandroid;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.parallelandroid.entity.Suit;
import com.google.android.material.imageview.ShapeableImageView;

import java.util.ArrayList;
import java.util.List;

public class SuitAdapter extends BaseAdapter {
    //上下文环境
    private Context mContext;
    //item的布局文件
    private  int layoutId;
    //数据源
    private List<Suit> suits = new ArrayList<>();
    private LinearLayout mLinearLayout;
    //给三个属性赋值的构造方法
    public SuitAdapter(Context mContext, int layoutId, List<Suit> suits) {
        this.mContext = mContext;
        this.layoutId = layoutId;
        this.suits = suits;
    }

    @Override
    public int getCount() {
        if (suits!=null){
            return suits.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int i) {
        if (suits!=null){
            return suits.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (view == null) {//判断view是否可以重载
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(mContext);
            mLinearLayout = (LinearLayout) inflater.inflate(R.layout.suit_item_main, null);
            viewHolder.tvUnlockName = mLinearLayout.findViewById(R.id.tv_unlockname);
            viewHolder.img = mLinearLayout.findViewById(R.id.iv_img);
            //设置数据
            viewHolder.tvUnlockName.setText(suits.get(i).getSuitName());
            //显示图片
            Glide.with(mContext).load(suits.get(i).getSuitSrc()).into(viewHolder.img);
            //标记当前view
            mLinearLayout.setTag(viewHolder);
        }else{//可以重载则直接使用原来的view
            mLinearLayout = (LinearLayout) view;
            viewHolder = (ViewHolder) mLinearLayout.getTag();
            viewHolder.tvUnlockName = mLinearLayout.findViewById(R.id.tv_unlockname);
            viewHolder.img = mLinearLayout.findViewById(R.id.iv_img);
            //设置数据
            viewHolder.tvUnlockName.setText(suits.get(i).getSuitName());
            //显示图片
            Glide.with(mContext).load(suits.get(i).getSuitSrc()).into(viewHolder.img);
        }
        return mLinearLayout;
    }

    private static class ViewHolder{
        //每一个item的控件
        TextView tvUnlockName;
        ShapeableImageView img;
    }
}
